﻿using System;
using System.Collections;
using System.Reflection;

namespace SimpleORM
{
    public abstract class TypeConverter : CDObject
    {
        #region Fields

        private Hashtable htc;

        #endregion

        #region Ctor

        public TypeConverter()
        {
            htc = TypeConverterAttribute.Create(this.GetType());
        }

        #endregion

        #region Methods

        #region Methods - Public

        public T To<T>(object source)
        {
            return (T)To(source, typeof(T));
        }

        public virtual object To(object source, Type target)
        {
            if (source == null)
                return null;

            if (source == DBNull.Value)
                return target.GetDefaultValue();

            if (target.IsEnum)
                return source is string ? Enum.Parse(target, (string)source) : Enum.ToObject(target, source);

            if (htc.ContainsKey(target))
                return (htc[target] as MethodInfo).Invoke(this, new object[] { source });

            return source;
        }

        #endregion

        #endregion
    }
}